import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import request from '../utils/request'
import Storage from '../utils/storage'

export interface UserProfile {
  id: number
  username: string
  nickname: string
  avatar: string
  email: string
  phone: string
  gender: 'male' | 'female' | 'unknown'
  birthday: string
  createTime: string
}

export const useUserStore = defineStore('user', () => {
  // 用户资料
  const profile = ref<UserProfile | null>(null)
  
  // 是否已登录
  const isLoggedIn = computed(() => !!profile.value)
  
  // Token
  const token = ref<string>('')

  /**
   * 登录
   */
  const login = async (username: string, password: string) => {
    try {
      const response = await request.post('/auth/login', {
        username,
        password
      })
      
      if (response.success) {
        token.value = response.data.token
        profile.value = response.data.user
        
        // 保存到本地存储
        Storage.set('token', token.value)
        Storage.set('userProfile', profile.value)
        
        return response
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('Login failed:', error)
      throw error
    }
  }

  /**
   * 注册
   */
  const register = async (userData: {
    username: string
    password: string
    email?: string
    phone?: string
  }) => {
    try {
      const response = await request.post('/auth/register', userData)
      
      if (response.success) {
        return response
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('Register failed:', error)
      throw error
    }
  }

  /**
   * 退出登录
   */
  const logout = async () => {
    try {
      await request.post('/auth/logout')
    } catch (error) {
      console.error('Logout request failed:', error)
    } finally {
      // 清除本地数据
      token.value = ''
      profile.value = null
      Storage.remove('token')
      Storage.remove('userProfile')
      
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/login'
      })
    }
  }

  /**
   * 获取用户信息
   */
  const fetchProfile = async () => {
    try {
      const response = await request.get('/user/profile')
      
      if (response.success) {
        profile.value = response.data
        Storage.set('userProfile', profile.value)
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('Fetch profile failed:', error)
      throw error
    }
  }

  /**
   * 更新用户信息
   */
  const updateProfile = async (data: Partial<UserProfile>) => {
    try {
      const response = await request.put('/user/profile', data)
      
      if (response.success) {
        profile.value = { ...profile.value!, ...response.data }
        Storage.set('userProfile', profile.value)
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('Update profile failed:', error)
      throw error
    }
  }

  /**
   * 上传头像
   */
  const uploadAvatar = async (filePath: string) => {
    try {
      const response = await request.upload('/user/avatar', filePath)
      
      if (response.success) {
        if (profile.value) {
          profile.value.avatar = response.data.url
          Storage.set('userProfile', profile.value)
        }
        return response.data
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('Upload avatar failed:', error)
      throw error
    }
  }

  /**
   * 修改密码
   */
  const changePassword = async (oldPassword: string, newPassword: string) => {
    try {
      const response = await request.post('/user/change-password', {
        oldPassword,
        newPassword
      })
      
      if (response.success) {
        return response
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('Change password failed:', error)
      throw error
    }
  }

  /**
   * 重置密码
   */
  const resetPassword = async (email: string) => {
    try {
      const response = await request.post('/auth/reset-password', {
        email
      })
      
      if (response.success) {
        return response
      } else {
        throw new Error(response.message)
      }
    } catch (error) {
      console.error('Reset password failed:', error)
      throw error
    }
  }

  /**
   * 从本地存储恢复用户信息
   */
  const restoreFromStorage = () => {
    const savedToken = Storage.get<string>('token')
    const savedProfile = Storage.get<UserProfile>('userProfile')
    
    if (savedToken && savedProfile) {
      token.value = savedToken
      profile.value = savedProfile
      
      // 验证token是否有效，如果无效则清除
      fetchProfile().catch(() => {
        logout()
      })
    }
  }

  // 初始化时恢复数据
  restoreFromStorage()

  return {
    // 状态
    profile,
    isLoggedIn,
    token,
    
    // 方法
    login,
    register,
    logout,
    fetchProfile,
    updateProfile,
    uploadAvatar,
    changePassword,
    resetPassword,
    restoreFromStorage
  }
})
